//
//  PictureDataViewController.m
//  GameBoss
//
//  Created by dllo on 15/4/21.
//  Copyright (c) 2015年 dllo. All rights reserved.
//

#import "PictureDataViewController.h"
#import "AFN_Get.h"
#import "UIImageView+WebCache.h"
#import "PicDataModel.h"

@interface PictureDataViewController ()

@property(nonatomic, retain)UIScrollView *scrollView;
@property(nonatomic, retain)NSMutableArray *picDataArr;
//设置点击状态
@property(nonatomic, assign)BOOL result;
//第一次点击会触发

@end

@implementation PictureDataViewController
-(instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.picDataArr = [NSMutableArray array];
#pragma mark 真为不隐藏navigationBar, 假为隐藏
        self.result = YES;
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationController.navigationBar.hidden = YES;
    
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:0.2 green:0.2 blue:0.2 alpha:0.5];
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager GET:self.picUrl parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {

        NSMutableArray *arr = [NSMutableArray array];
        arr = responseObject[@"photos"];
        self.picDataArr = [NSMutableArray array];
        for (NSDictionary *temp in arr) {
            PicDataModel *model = [[PicDataModel alloc] init];
            [model setValuesForKeysWithDictionary:temp];
            [self.picDataArr addObject:model];
            [model release];
        }
        
        self.scrollView.contentSize = CGSizeMake(self.picDataArr.count * Screen.width, Screen.height);
        
        for (int i = 0; i<self.picDataArr.count; i++) {
#pragma mark 设置小的控制器 控制放大缩小
            UIScrollView *scroll = [[UIScrollView alloc] initWithFrame:CGRectMake(Screen.width * i, 0, Screen.width, Screen.height)];
            [self.scrollView addSubview:scroll];
            scroll.delegate = self;
            
            //imageView
            UIImageView *imageView = [[UIImageView alloc] init];
            
            PicDataModel *model = self.picDataArr[i];
            //获取图片操作
            [imageView sd_setImageWithURL:[NSURL URLWithString:model.url]];
            imageView.frame = CGRectMake(0, -49, Screen.width, Screen.height);
            imageView.center = CGPointMake(Screen.width/2, Screen.height/2);
            //图片自动适应相框(无论图片是长方形,正方形,都只会按照原来的比例显示在相框里)
            imageView.contentMode = UIViewContentModeScaleAspectFit;
            imageView.autoresizesSubviews = YES;
//            imageView.autoresizingMask = UIViewAutoresizingFlexibleHeight;
            // 剪掉超出相框的部分,这里不需要
            //            imageView.clipsToBounds = YES;
            
            [scroll addSubview:imageView];
            [imageView release];
            [scroll release];
            
#pragma mark 设置view显示简单详情
            UIView *hiddenView = [[UIView alloc] initWithFrame:CGRectMake(Screen.width * 10/375, Screen.height * 6/7, Screen.width - Screen.width * 20/375, Screen.height * 80/667)];
            hiddenView.layer.cornerRadius = 5;
            hiddenView.backgroundColor = [UIColor colorWithRed:0.1 green:0.1 blue:0.1 alpha:0.5];
            [imageView addSubview:hiddenView];
            hiddenView.tag = 1000 + i;
            [hiddenView release];
 
            //name  label
            UILabel *labelName = [[UILabel alloc] initWithFrame:CGRectMake(Screen.width * 15/375, Screen.height * 10/667, Screen.width - Screen.width * 40/375, Screen.height * 30/667)];
            labelName.text = [self.picDataArr[i] name];
            //            labelName.font = [UIFont systemFontOfSize:14];
            labelName.textColor = [UIColor whiteColor];
            [hiddenView addSubview:labelName];
            [labelName release];
            //第几张图片
            UILabel *labelNum = [[UILabel alloc] initWithFrame:CGRectMake(Screen.width * 10/375, Screen.height * 40/667, Screen.width * 50/375, Screen.height * 20/667)];
            labelNum.text = [NSString stringWithFormat:@"%d/%ld", i+1, self.picDataArr.count];
            labelNum.textColor = [UIColor whiteColor];
            labelNum.font = [UIFont fontWithName:@"AppleGothic" size:12];
            [hiddenView addSubview:labelNum];
            [labelNum release];
#pragma mark  设置下载到本地功能按钮

            UIButton *dowenload = [UIButton buttonWithType:UIButtonTypeSystem];
            dowenload.frame = CGRectMake(Screen.width * 3/4, Screen.height * 30/667, Screen.width * 40/375, Screen.height * 40/667);
            [hiddenView addSubview:dowenload];
            [dowenload setImage:[UIImage imageNamed:@"iconfont-xiazai"] forState:UIControlStateNormal];
            dowenload.tintColor = [UIColor colorWithRed:244/250.0 green:244/250.0 blue:244/250.0 alpha:1];
            [dowenload addTarget:self action:@selector(dowenClick:) forControlEvents:UIControlEventTouchUpInside];
            
            hiddenView.hidden = YES;
            
#pragma mark 开启图片的相互交互
            imageView.userInteractionEnabled = YES;
            UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
            //点击一次触发
            tap.numberOfTapsRequired = 1;
            [imageView addGestureRecognizer:tap];
            [tap release];
            
            //放大缩小
            scroll.minimumZoomScale = 1;
            scroll.maximumZoomScale = 5;
        }

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"解析失败");
        NSLog(@"error:%@", error);
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"提示" message:@"网络连接失败" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
        [self.view addSubview:alertView];
        [alertView show];
        [alertView release];
    }];
    
#pragma mark 设置个大的图片控制器
    self.scrollView = [[UIScrollView alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    [self.view addSubview:self.scrollView];
    [_scrollView release];
    self.scrollView.delegate = self;
    self.scrollView.pagingEnabled = YES;
    self.scrollView.directionalLockEnabled = YES;
#pragma mark 设置scrollView不能变动,也不能翻页了
//    self.scrollView.scrollEnabled = NO;
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"fanhui"] style:UIBarButtonItemStyleDone target:self action:@selector(returnClick:)];
}
#pragma mark 延迟结束
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    #pragma mark 设置缩放还原功能
    //设置缩放还原
    for (UIScrollView *subView in scrollView.subviews)
    {
        if ([subView isKindOfClass:[UIScrollView class]])
        {
            [subView setZoomScale:1.0];
        }
    }
    if (self.scrollView.contentOffset.x != 0) {
        self.navigationController.navigationBar.hidden = YES;
        NSInteger page = self.scrollView.contentOffset.x/Screen.width;
        [self.view viewWithTag:(1000 + page - 1)].hidden = YES;
        [self.view viewWithTag:(1000 + page + 1)].hidden = YES;
        _result = YES;
    }
}
#pragma mark 设置缩放功能
-(UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView{
    
    return [scrollView.subviews firstObject];
}
#pragma mark tap点击触发事件
-(void)tapAction:(UITapGestureRecognizer *)tap{
    if (_result) {
        self.navigationController.navigationBar.hidden = NO;
        NSInteger page = self.scrollView.contentOffset.x/Screen.width;
        [self.view viewWithTag:(1000 + page)].hidden = NO;
    }else{
        self.navigationController.navigationBar.hidden = YES;
        NSInteger page = self.scrollView.contentOffset.x/Screen.width;
        [self.view viewWithTag:(1000 + page)].hidden = YES;
    }
    _result = !_result;
}

-(void)returnClick:(id)sender{
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark 设置下载到本地功能
-(void)dowenClick:(id)sender{
    UIImageView *imageView = [[UIImageView alloc] init];
    NSInteger page = self.scrollView.contentOffset.x/Screen.width;
    PicDataModel *model = self.picDataArr[page];
    [imageView sd_setImageWithURL:[NSURL URLWithString:model.url] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        [self saveImageToPhotos:image];
    }];
}

- (void)saveImageToPhotos:(UIImage*)image
{
    UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError:contextInfo:), NULL);
}

- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error
  contextInfo:(void *)contextInfo
{
    if (error != NULL)
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"下载图片失败!" delegate:self cancelButtonTitle:@"确认" otherButtonTitles: nil];
        [alert show];
        [alert release];
    }
    else
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"下载图片成功!" delegate:self cancelButtonTitle:@"确认" otherButtonTitles: nil];
        [alert show];
        [alert release];
    }
}

- (void)dealloc
{
    [_picDataArr release];
    [_scrollView release];
    [super dealloc];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
